package org.pitest.ant.util;

import javassist.ClassPool;
import javassist.CtClass;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Logger;

/**
 */
public class ClassUtils {
  /**
   * Logging instance.
   */
  private static Logger s_log = Logger.getLogger(ClassUtils.class.getName());

  /**
   * {@see ClassPool} instance, used to save class definitions.
   */
  private static ClassPool CLASS_POOL = ClassPool.getDefault();

  /**
   * Helper method that will use the javaassist {@see ClassPool} to load a class from the provided {@see File}
   * and return the name of the class.
   * <p/>
   * Will throw a {@see IllegalArgumentException} if the file cannot be read, or if the file is not a java class file.
   *
   * @param f the {@see File} to attempt to parse.
   * @return the name of the class in the provided {@see File}.
   * @throws IllegalArgumentException if the file cannot be read, or if the file is not a java class file.
   */
  public static String getClassName(File f) throws IllegalArgumentException {
    try {
      CtClass clazz = CLASS_POOL.makeClass(new FileInputStream(f));
      return clazz.getName();
    } catch (IOException e) {
      throw new IllegalArgumentException("IOException thrown parsing " + f.getAbsolutePath() + ".");
    } catch (RuntimeException e) {
      throw new IllegalArgumentException("IOException thrown parsing " + f.getAbsolutePath() + ".");
    }
  }
}
